let crypto = require('crypto')

const exUtil = {
  randomString: function (len) {
    len = len || 32
    // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    const maxPos = chars.length
    let pwd = ''
    for (let i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
  },
  md5: function (str) {
    let hasher = crypto.createHash('md5')
    return hasher.update(str).digest('hex')
  },
  passwordMd5: function (str, salt) {
    let tmpStr = this.md5(str)
    return this.md5(tmpStr + '_' + salt)
  },
  nowTime: function () {
    return Date.now() / 1000
  },
  formatDateTime: function (inputTime) {
    let date = new Date(inputTime)
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    m = m < 10 ? ('0' + m) : m
    let d = date.getDate()
    d = d < 10 ? ('0' + d) : d
    let h = date.getHours()
    h = h < 10 ? ('0' + h) : h
    let minute = date.getMinutes()
    let second = date.getSeconds()
    minute = minute < 10 ? ('0' + minute) : minute
    second = second < 10 ? ('0' + second) : second
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
  },
  stripHtml: function (htmlStr) {
    let reTag = /<(?:.|\s)*?>/g
    return htmlStr.replace(reTag, '')
  },
  subStr: function (str, len = 150) {
    if (str.length < len)
    {
      return str
    }

    return str.substr(0, len) + ' ...'
  }
}

module.exports = exUtil
